package com.czy.security.service.impl;

import com.czy.security.entity.Admin;
import com.czy.security.service.AdminService;
import com.czy.security.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @作者:褚
 * @工程名:spring_security
 * @方法:UserDetailServiceImpl
 * @创建时间:2022/4/12 15:02
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.login(username);
        if (admin==null){
            throw new UsernameNotFoundException("用户名称错误");
        }
        List<String> roleList = roleService.getRoleById(admin.getAid());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String rolename:roleList){
            authorities.add(new SimpleGrantedAuthority(rolename));
        }
        return new User(username,admin.getApwd(),authorities);
    }
}
